import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { ValidationPipe } from '@nestjs/common';
import rateLimit from 'express-rate-limit';
import helmet from 'helmet';
import { AppModule } from './app.module';
import {
  ErrorsInterceptor,
  TransformInterceptor,
} from './global/transform.interceptor';
import { HttpFilterFilter } from './global/http-filter.filter';

async function bootstrap() {
  // cors 允许前端跨域
  const app = await NestFactory.create(AppModule, { cors: true });

  //配置swagger
  const swaggerOptions = new DocumentBuilder()
    .setTitle('nestjs-api-文档') //文档标题
    .setDescription('/doc-json') //文档描述
    .setVersion('1.0') //文档版本
    .build(); //创建
  //创建swagger
  const document = SwaggerModule.createDocument(app, swaggerOptions);
  //启动swagger
  SwaggerModule.setup('doc', app, document); //访问路径为 localhost:8000/doc localhost:8000/doc-json

  app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));
  app.setGlobalPrefix('/api');
  app.useGlobalFilters(
    new HttpFilterFilter(app.get(WINSTON_MODULE_NEST_PROVIDER)),
  );
  app.useGlobalPipes(
    new ValidationPipe({
      // 去除前端传递dto上没有的字段
      whitelist: true,
    }),
  );
  app.useGlobalInterceptors(
    new ErrorsInterceptor(),
    new TransformInterceptor(),
  );
  // 限速
  // app.use(
  //   rateLimit({
  //     windowMs: 15 * 60 * 1000, // 15 minutes
  //     max: 100, // limit each IP to 100 requests per windowMs
  //   }),
  // );
  // 头部安全
  // app.use(helmet());
  await app.listen(9000);
}
bootstrap();
